package com.ttxs.fileformathandling.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.gson.Gson;

import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.ttxs.apiclientsdk.client.CwtApiClient;
import com.ttxs.apiclientsdk.model.RequestObj;
import com.ttxs.apicommon.model.entity.Api;
import com.ttxs.apicommon.model.entity.User;
import com.ttxs.fileformathandling.annotation.AuthCheck;
import com.ttxs.fileformathandling.common.*;
import com.ttxs.fileformathandling.constant.CommonConstant;
import com.ttxs.fileformathandling.constant.UserConstant;
import com.ttxs.fileformathandling.exception.BusinessException;
import com.ttxs.fileformathandling.exception.ThrowUtils;
import com.ttxs.fileformathandling.model.dto.api.ApiAddRequest;
import com.ttxs.fileformathandling.model.dto.api.ApiInvokeRequest;
import com.ttxs.fileformathandling.model.dto.api.ApiQueryRequest;
import com.ttxs.fileformathandling.model.dto.api.ApiUpdateRequest;
import com.ttxs.fileformathandling.model.enums.ApiStatusEnum;
import com.ttxs.fileformathandling.service.ApiService;
import com.ttxs.fileformathandling.service.UserApiInfoService;
import com.ttxs.fileformathandling.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * API接口
 *
 * @author cwt
 */
@RestController
@RequestMapping("/api")
@Slf4j
public class ApiController {

    @Resource
    private ApiService apiService;

    @Resource
    private UserService userService;

    @Resource
    private UserApiInfoService userApiInfoService;

    @Resource
    private CwtApiClient cwtApiClient;

    // region 增删改查

    /**
     * 创建
     *
     * @param apiAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addApi(ApiAddRequest apiAddRequest, HttpServletRequest request) {
        if (apiAddRequest == null || apiAddRequest.getFile() == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数不能为空");
        }
        MultipartFile file = apiAddRequest.getFile();
        String originalFilename = file.getOriginalFilename();
        assert originalFilename != null;
        String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
        if (!"jar".equals(fileSuffix)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "暂不支持除JAR类型的插件");
        }
        File inDir = new File("D:\\projects\\idea\\api-interface\\plugin-app\\target\\classes\\plugins\\");
        if (!inDir.exists()) {
            if (!inDir.mkdirs()) {
                throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件目录创建失败");
            }
        }
        //保存文件
        File inFile = new File(inDir, originalFilename);
        try {
            file.transferTo(inFile); //转换文件
        } catch (IOException e) {
            e.printStackTrace();
        }

        Api api = new Api();
        BeanUtils.copyProperties(apiAddRequest, api);

        apiService.validApi(api, true);
        User loginUser = userService.getLoginUser(request);
        api.setUserId(loginUser.getId());

        //热加载插件
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        String url = "http://localhost:8082/api/hot/loaders";
        CwtApiClient tempClient = new CwtApiClient(accessKey, secretKey, url);
        System.out.println(tempClient.requestLoadJars());

        boolean result = apiService.save(api);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        long newApiId = api.getId();
        return ResultUtils.success(newApiId);
    }

    /**
     * 删除
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteApi(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Api oldApi = apiService.getById(id);
        ThrowUtils.throwIf(oldApi == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldApi.getUserId().equals(user.getId()) && userService.notAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        boolean b = apiService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param apiUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateApi(ApiUpdateRequest apiUpdateRequest, HttpServletRequest request) {
        if (apiUpdateRequest == null || apiUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        User loginUser = userService.getLoginUser(request);

        MultipartFile file = apiUpdateRequest.getFile();
        if (file != null) {
            String originalFilename = file.getOriginalFilename();
            assert originalFilename != null;
            String fileSuffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
            if (!"jar".equals(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "暂不支持除JAR类型的插件");
            }
            File inDir = new File("D:\\projects\\idea\\api-interface\\plugin-app\\target\\classes\\plugins\\");
            if (!inDir.exists()) {
                if (!inDir.mkdirs()) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "文件目录创建失败");
                }
            }
            //保存文件
            File inFile = new File(inDir, originalFilename);
            try {
                file.transferTo(inFile); //转换文件
            } catch (IOException e) {
                e.printStackTrace();
            }

            //热加载插件
            String accessKey = loginUser.getAccessKey();
            String secretKey = loginUser.getSecretKey();
            String url = "http://localhost:8082/api/hot/loaders";
            CwtApiClient tempClient = new CwtApiClient(accessKey, secretKey, url);
            System.out.println(tempClient.requestLoadJars());
        }

        Api api = new Api();
        BeanUtils.copyProperties(apiUpdateRequest, api);

        // 参数校验
        apiService.validApi(api, false);
        long id = apiUpdateRequest.getId();
        // 判断是否存在
        Api oldApi = apiService.getById(id);
        ThrowUtils.throwIf(oldApi == null, ErrorCode.NOT_FOUND_ERROR);
        boolean result = apiService.updateById(api);
        return ResultUtils.success(result);
    }

    /**
     * 根据 id 获取
     *
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Api> getApiById(long id) {
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Api api = apiService.getById(id);
        if (api == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        return ResultUtils.success(api);
    }

    /**
     * 分页获取列表（封装类）
     *
     * @param apiQueryRequest
     * @return
     */
    @PostMapping("/list")
    public BaseResponse<List<Api>> listApi(@RequestBody ApiQueryRequest apiQueryRequest) {
        Api api = new Api();
        if (apiQueryRequest != null) {
            BeanUtils.copyProperties(apiQueryRequest, api);
        }
        QueryWrapper<Api> queryWrapper = new QueryWrapper<>(api);
        List<Api> apiList = apiService.list(queryWrapper);
        return ResultUtils.success(apiList);
    }

    /**
     * 分页获取当前用户创建的资源列表
     *
     * @param apiQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page")
    public BaseResponse<Page<Api>> listApiByPage(@RequestBody ApiQueryRequest apiQueryRequest,
                                                 HttpServletRequest request) {
        if (apiQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Api api = new Api();
        BeanUtils.copyProperties(apiQueryRequest, api);
        String sortField = apiQueryRequest.getSortField();
        String sortOrder = apiQueryRequest.getSortOrder();
        String description = api.getDescription();
        long current = apiQueryRequest.getCurrent();
        long size = apiQueryRequest.getPageSize();
        // description 需支持模糊搜索
        api.setDescription(null);
        // 限制爬虫
        ThrowUtils.throwIf(size > 50, ErrorCode.PARAMS_ERROR);
        QueryWrapper<Api> queryWrapper = new QueryWrapper<>(api);
        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
        queryWrapper.orderBy(StringUtils.isNotBlank(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        queryWrapper.orderByDesc("status");
        Page<Api> apiPage = apiService.page(new Page<>(current, size), queryWrapper);
        return ResultUtils.success(apiPage);
    }

    // endregion

    /**
     * 发布
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/online")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> onlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                     HttpServletRequest request) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = idRequest.getId();
        // 判断是否存在
        Api oldInterfaceInfo = apiService.getById(id);
        if (oldInterfaceInfo == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 判断该接口是否可以调用
        RequestObj obj = new RequestObj();
        obj.setContent("test");
        String res = cwtApiClient.restfulRequest(obj);
        if (StringUtils.isBlank(res)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败");
        }
        // 仅本人或管理员可修改
        Api api = new Api();
        api.setId(id);
        api.setStatus(ApiStatusEnum.ONLINE.getValue());
        boolean result = apiService.updateById(api);
        return ResultUtils.success(result);
    }

    /**
     * 下线
     *
     * @param idRequest
     * @param request
     * @return
     */
    @PostMapping("/offline")
    @AuthCheck(mustRole = "admin")
    public BaseResponse<Boolean> offlineInterfaceInfo(@RequestBody IdRequest idRequest,
                                                      HttpServletRequest request) {
        if (idRequest == null || idRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = idRequest.getId();
        // 判断是否存在
        Api apiServiceById = apiService.getById(id);
        if (apiServiceById == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 判断该接口是否可以调用
        RequestObj obj = new RequestObj();
        obj.setContent("test");
        String res = cwtApiClient.restfulRequest(obj);
        if (StringUtils.isBlank(res)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "接口验证失败");
        }
        // 仅本人或管理员可修改
        Api api = new Api();
        api.setId(id);
        api.setStatus(ApiStatusEnum.OFFLINE.getValue());
        boolean result = apiService.updateById(api);
        return ResultUtils.success(result);
    }

    /**
     * 测试调用
     *
     * @param apiInvokeRequest
     * @param request
     * @return
     */
    @PostMapping("/invoke")
    public BaseResponse<Object> invokeInterfaceInfo(@RequestBody ApiInvokeRequest apiInvokeRequest,
                                                    HttpServletRequest request) {
        if (apiInvokeRequest == null || apiInvokeRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = apiInvokeRequest.getId();
        User loginUser = userService.getLoginUser(request);

        // 判断是否存在
        Api oldApi = apiService.getById(id);
        if (oldApi == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        if (oldApi.getStatus() == ApiStatusEnum.OFFLINE.getValue()) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "接口未上线");
        }
        if (!userApiInfoService.validExist(loginUser.getId(), id)) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "用户接口记录创建失败");
        }

        String url = oldApi.getUrl();
        String userRequestParam = apiInvokeRequest.getUserRequestParam();

        //使用自己的accessKey secretKey
        String accessKey = loginUser.getAccessKey();
        String secretKey = loginUser.getSecretKey();
        CwtApiClient tempClient = new CwtApiClient(accessKey, secretKey, url);
        Gson gson = new Gson();
        RequestObj obj = gson.fromJson(userRequestParam, RequestObj.class);
        obj.setClazz(oldApi.getName());
        String result = tempClient.restfulRequest(obj);
        return ResultUtils.success(result);
    }

}
